package com.github.postsanf.yinian.huanxin.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.bean.YNHistory;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.huanxin.Constant;
import com.github.postsanf.yinian.huanxin.DemoHelper;
import com.github.postsanf.yinian.huanxin.domain.RobotUser;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.util.EasyUtils;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.LinkedHashMap;
import java.util.Map;

import easeui.ui.EaseChatHistoryFragment2;
import easeui.widget.chatrow.EaseChatHistoryRow2;
import easeui.widget.chatrow.EaseCustomChatRowHistoryProvider2;

public class ChatHistoryFragment2 extends EaseChatHistoryFragment2 implements EaseChatHistoryFragment2.EaseChatFragmentHelper {

    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_AT_USER = 15;

    /**
     * if it is chatBot
     */
    private boolean isRobot;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionChatDelteStatus);
        myIntentFilter.addAction(ACTIONs.actionHuanXinAlertGName);
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionChatDelteStatus:
                    String msgId = intent.getStringExtra("msgId");
                    if (!StringUtils.isEmpty(msgId)) {
                        conversation.removeMessage(msgId);
                        messageList.refresh();
                    }
                    break;
                case ACTIONs.actionHuanXinAlertGName:
                    String gname = intent.getStringExtra("gName");
                    if (!StringUtils.isEmpty(gname)) {
                        titleBar.setTitle(gname);
                    }
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    protected void setUpView() {
        setChatFragmentListener(this);
        if (chatType == Constant.CHATTYPE_SINGLE) {
            Map<String, RobotUser> robotMap = DemoHelper.getInstance().getRobotList();
            if (robotMap != null && robotMap.containsKey(toChatUsername)) {
                isRobot = true;
            }
        }
        super.setUpView();
        // set click listener
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (EasyUtils.isSingleActivity(getActivity())) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                }
                onBackPressed();
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
        }
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_AT_USER:
                    if (data != null) {
                        String username = data.getStringExtra("username");
                    }
                    break;
                default:
                    break;
            }
        }
    }


    // 删除该条动态
    private void doDeleteStatus(final int eid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(eid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynDeleteEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resDelete = new Gson().fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resDelete.getCode())) {
                            Intent mIntent = new Intent(ACTIONs.actionStatus);
                            // 同步删除动态
                            mIntent.putExtra(ACTIONs.IsAdd, false);
                            mIntent.putExtra(ACTIONs.StatusId, eid);
                            //发送广播,通知更新
                            getActivity().sendBroadcast(mIntent);
                            if (getActivity().getIntent().getBooleanExtra("detail", false)) {
                                getActivity().sendBroadcast(new Intent(ACTIONs.McardDetailFinish));
                            }
                        } else {
                            Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(getActivity())).executeAsync(req);
    }

    @Override
    public void onSetMessageAttributes(YNHistory message) {
    }

    @Override
    public EaseCustomChatRowHistoryProvider2 onSetCustomChatRowProvider() {
        return new CustomChatRowProvider2();
    }


    @Override
    public void onEnterToChatDetails() {
        if (chatType == Constant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            startActivityForResult(
                    (new Intent(getActivity(), GroupDetailsActivity.class).putExtra("groupId", toChatUsername)),
                    REQUEST_CODE_GROUP_DETAIL);
        } else if (chatType == Constant.CHATTYPE_CHATROOM) {
            startActivityForResult(new Intent(getActivity(), ChatRoomDetailsActivity.class).putExtra("roomId", toChatUsername), REQUEST_CODE_GROUP_DETAIL);
        }
    }

    @Override
    public void onAvatarClick(String username) {
    }

    @Override
    public void onAvatarLongClick(String username) {
    }


    @Override
    public boolean onMessageBubbleClick(YNHistory message) {
        return false;
    }


    @Override
    public void onMessageBubbleLongClick(YNHistory message) {
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
//            case ITEM_VIDEO:
//                Intent intent = new Intent(getActivity(), ImageGridActivity.class);
//                startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
//                break;
//        case ITEM_FILE: //file
//            selectFileFromLocal();
//            break;
//        case ITEM_VOICE_CALL:
//            startVoiceCall();
//            break;
//        case ITEM_VIDEO_CALL:
//            startVideoCall();
//            break;
            //red packet code : 进入发红包页面
//        case ITEM_RED_PACKET:
//            RedPacketUtil.startRedPacketActivityForResult(this, chatType, toChatUsername, REQUEST_CODE_SEND_RED_PACKET);
//            break;
            //end of red packet code
            default:
                break;
        }
        //keep exist extend menu
        return false;
    }


    /**
     * chat row provider
     */
    private final class CustomChatRowProvider2 implements EaseCustomChatRowHistoryProvider2 {
        @Override
        public int getCustomChatRowTypeCount() {
            return 8;
        }

        @Override
        public int getCustomChatRowType(YNHistory message) {
//
//            if (message.getPayload().getBodies().get(0).getType().equals("txt")) {
//                //voice call
//                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
//                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
//                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
//                    //video call
//                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
//                }
//            }
            return 0;
        }

        @Override
        public EaseChatHistoryRow2 getCustomChatRow(YNHistory message, int position, BaseAdapter adapter) {
            return null;
        }

    }

}
